/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.medication.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.billing.domain.BillingInfo;
import com.jeeplus.billing.service.BillingInfoService;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.drug.domain.DrugInfo;
import com.jeeplus.drug.service.DrugInfoService;
import com.jeeplus.follow.domain.FollowUpInfo;
import com.jeeplus.follow.service.FollowUpInfoService;
import com.jeeplus.medication.service.MedicationInfoService;
import com.jeeplus.medication.service.dto.MedicationInfoDTO;
import com.jeeplus.medication.service.mapstruct.MedicationInfoWrapper;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 处方信息Controller
 * @author xx
 * @version 2024-02-18
 */

@Api(tags ="处方信息")
@RestController
@RequestMapping(value = "/medication/medicationInfo")
public class MedicationInfoController {

	@Autowired
	private MedicationInfoService medicationInfoService;

	@Autowired
	private MedicationInfoWrapper medicationInfoWrapper;

	@Resource
	private DrugInfoService drugInfoService;

	@Resource
	private BillingInfoService billingInfoService;

	@Resource
	private FollowUpInfoService followUpInfoService;
	/**
	 * 处方信息列表数据
	 */
	@ApiLog("查询处方信息列表数据")
	@ApiOperation(value = "查询处方信息列表数据")
	@PreAuthorize("hasAuthority('medication:medicationInfo:list')")
	@GetMapping("list")
	public ResponseEntity<IPage<MedicationInfoDTO>> list(MedicationInfoDTO medicationInfoDTO, Page<MedicationInfoDTO> page) throws Exception {
		List<RoleDTO> roleDTOS = UserUtils.getCurrentUserDTO().getRoleDTOList();
		if (!CollectionUtils.isEmpty(roleDTOS)) {
			if (roleDTOS.stream().anyMatch(role -> "patient".equals(role.getEnName()))) {
				medicationInfoDTO.setPatientId(UserUtils.getCurrentUserDTO().getId());
			}
		}
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (medicationInfoDTO, MedicationInfoDTO.class);
		IPage<MedicationInfoDTO> result = medicationInfoService.findPage (page, queryWrapper);
		return ResponseEntity.ok (result);
	}


	/**
	 * 根据Id获取处方信息数据
	 */
	@ApiLog("根据Id获取处方信息数据")
	@ApiOperation(value = "根据Id获取处方信息数据")
	@PreAuthorize("hasAnyAuthority('medication:medicationInfo:view','medication:medicationInfo:add','medication:medicationInfo:edit')")
	@GetMapping("queryById")
	public ResponseEntity<MedicationInfoDTO> queryById(String id) {
		return ResponseEntity.ok ( medicationInfoService.findById ( id ) );
	}

	/**
	 * 保存处方信息
	 */
	@ApiLog("保存处方信息")
	@ApiOperation(value = "保存处方信息")
	@PreAuthorize("hasAnyAuthority('medication:medicationInfo:add','medication:medicationInfo:edit')")
	@PostMapping("save")
	public  ResponseEntity <String> save(@Valid @RequestBody MedicationInfoDTO medicationInfoDTO) {
		//新增或编辑表单保存
		medicationInfoService.saveOrUpdate (medicationInfoWrapper.toEntity (medicationInfoDTO));
		// 添加费用清单
		if(StrUtil.isBlank(medicationInfoDTO.getId())){
			String drugId = medicationInfoDTO.getMedicationName();
			DrugInfo drugInfo = drugInfoService.getById(drugId);
			BillingInfo billingInfo = new BillingInfo();
			billingInfo.setPatientId(medicationInfoDTO.getPatientId());
			billingInfo.setVisitId(medicationInfoDTO.getVisitId());
			billingInfo.setAmount(Integer.parseInt(medicationInfoDTO.getDuration()));
			billingInfo.setConsumptionItem(medicationInfoDTO.getMedicationName());
			billingInfo.setPaymentStatus("1");
			billingInfo.setPaymentMethod("1");
			billingInfo.setCost(drugInfo.getUnitPrice()* billingInfo.getAmount());
			billingInfo.setUnitPrice(drugInfo.getUnitPrice());
			billingInfoService.save(billingInfo);

			if (!medicationInfoDTO.getFollowUpTime().isEmpty()){
				//添加回访计划
				FollowUpInfo followUpInfo = new FollowUpInfo();
				followUpInfo.setFollowName("用药回访");
				followUpInfo.setPatientId(medicationInfoDTO.getPatientId());
				followUpInfo.setDoctorId(medicationInfoDTO.getDoctorId());

				// 获取当前日期
				Date today = new Date();
				System.out.println("当前日期是: " + today);

				// 获取Calendar实例
				Calendar calendar = Calendar.getInstance();
				// 设置Calendar时间为当前日期
				calendar.setTime(today);

				if (medicationInfoDTO.getFollowUpTime().equals("1")){
					calendar.add(Calendar.DAY_OF_MONTH, 7);
				}else {
					calendar.add(Calendar.DAY_OF_MONTH, 14);
				}

				followUpInfo.setFollowUpDate(calendar.getTime());
				followUpInfoService.save(followUpInfo);
			}

			if (medicationInfoDTO.getManyiduTime() != null){
				//添加满意度调查
				FollowUpInfo followUpInfo = new FollowUpInfo();
				followUpInfo.setFollowName("用药满意度调查");
				followUpInfo.setPatientId(medicationInfoDTO.getPatientId());
				followUpInfo.setDoctorId(medicationInfoDTO.getDoctorId());
				followUpInfo.setFollowUpDate(medicationInfoDTO.getManyiduTime());
				followUpInfo.setFollowtype("2");
				followUpInfoService.save(followUpInfo);
			}


		}
        return ResponseEntity.ok ( "保存处方信息成功" );
	}


	/**
	 * 删除处方信息
	 */
	@ApiLog("删除处方信息")
	@ApiOperation(value = "删除处方信息")
	@PreAuthorize("hasAuthority('medication:medicationInfo:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        medicationInfoService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除处方信息成功" );
	}
	
	/**
     * 导出处方信息数据
     *
     * @param medicationInfoDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出处方信息数据")
    @PreAuthorize("hasAnyAuthority('medication:medicationInfo:export')")
    @GetMapping("export")
    public void exportFile(MedicationInfoDTO medicationInfoDTO, Page <MedicationInfoDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (medicationInfoDTO, MedicationInfoDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据
            
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "a.id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List<MedicationInfoDTO> result = medicationInfoService.findPage ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( medicationInfoService, medicationInfoWrapper ).exportExcel ( result,  options.getSheetName ( ), MedicationInfoDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入处方信息数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('medication:medicationInfo:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( medicationInfoService, medicationInfoWrapper ).importExcel ( file, MedicationInfoDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入处方信息数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('medication:medicationInfo:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "处方信息数据导入模板.xlsx";
        List<MedicationInfoDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( medicationInfoService, medicationInfoWrapper ).exportExcel ( list,  "处方信息数据", MedicationInfoDTO.class, fileName, null, response );
    }

}
